<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item prop="name" label="单位名称">
            <el-input
              v-model="baTable.form.items!.name"
              type="string"
              placeholder="单位名称"
            ></el-input>
          </el-form-item>
          <el-form-item prop="type" label="所属行业">
            <el-input
              v-model="baTable.form.items!.type"
              type="string"
              placeholder="所属行业"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属区域" prop="region">
            <el-tree
              ref="treeRef"
              :default-checked-keys="
                baTable.form.operate == 'edit'
                  ? [baTable.form.items.regionbo]
                  : []
              "
              show-checkbox
              node-key="areaId"
              :props="{
                children: 'children',
                label: 'areaName',
                value: 'areaId',
              }"
              :data="state.regionOptions"
              @check="handleCheckChange"
            />
          </el-form-item>
          <el-form-item prop="addr" label="地址">
            <el-input
              v-model="baTable.form.items!.addr"
              type="string"
              placeholder="输入详细地址后(精确到号)"
            ></el-input>
          </el-form-item>
          <el-form-item prop="creditCode" label="企业社会信用代码">
            <el-input
              v-model="baTable.form.items!.creditCode"
              type="string"
              placeholder="企业社会信用代码"
            ></el-input>
          </el-form-item>
          <FormItem
            label="状态"
            v-model="baTable.form.items!.state"
            type="radio"
            :data="{
              content: { 0: '正常', 1: '异常' },
              childrenAttr: { border: true },
            }"
          />
          <el-form-item prop="user" label="联系人">
            <el-input
              v-model="baTable.form.items!.user"
              type="string"
              placeholder="联系人"
            ></el-input>
          </el-form-item>
          <el-form-item prop="tel" label="联系方式">
            <el-input
              v-model="baTable.form.items!.tel"
              type="string"
              placeholder="联系电话"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref, inject, onMounted, watch, nextTick } from "vue";
import type baTableClass from "@/utils/baTable";
import type { ElForm, FormItemRule, FormRules, ElTree } from "element-plus";
import FormItem from "@/components/formItem/index.vue";
import { useBusiness } from "@/store/backend/BusinessM/info";
import { useRegion } from "@/store/backend/SysM/region";
import { res } from "virtual";
import { Check } from "@element-plus/icons-vue";

const formRef = ref<InstanceType<typeof ElForm>>();
const baTable = inject("baTable") as baTableClass;
const business = useBusiness();
const region = useRegion();
const treeRef = ref<InstanceType<typeof ElTree>>();

const state: {
  regionOptions: anyObj[];
} = reactive({
  regionOptions: [], //区域列表
});

const props = {
  label: "areaName",
  value: "areaId",
  children: "children",
};

const rules = reactive<FormRules>({
  name: [{ required: true, message: "企业/单位名称不能为空", trigger: "blur" }],
  region: [
    {
      required: true,
      validator: (rule: any, val: string, callback: Function) => {
        let ids = getCheckeds();
        if (ids.length <= 0) {
          return callback(new Error("请选择区域"));
        }
        return callback();
      },
    },
  ],
  addr: [{ required: true, message: "地址不能为空", trigger: "blur" }],
  user: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
  tel: [{ required: true, message: "联系方式不能为空", trigger: "blur" }],
});

const handleCheckChange = (data: any, node: any) => {
  console.log("data", data, "node", node);
  baTable.form.items!.regionName = data.areaName;
};

//包含所有的层级id
const getCheckeds = () => {
  return treeRef
    .value!.getCheckedKeys()
    .concat(treeRef.value!.getHalfCheckedKeys());
};
//获取最后一级id
const getCheckedOne = () => {
  return treeRef.value!.getCheckedKeys();
};

onMounted(() => {
  //使用获取区域列表
  region.getRegionByRole().then((res: any) => {
    console.log("state.regionOptions", res);
    state.regionOptions = res;
  });
});
watch(
  () => baTable.form.operate,
  (newValue, oldValue) => {
    console.log("newValue", newValue);
    if (newValue === "add") {
      nextTick(() => {
        treeRef.value!.setCheckedKeys([], false);
      });
    }
  },
  {
    immediate: true, // 值如果是true会打开首次监听
  }
);
defineExpose({
  getCheckeds,
  getCheckedOne,
});
</script>
<style lang="scss" scoped>
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
</style>
